#!/bin/sh

# 尝试自动检测WiFi客户端接口
detect_wifi_iface() {
    # 方法1：通过路由表查找默认路由使用的无线接口
    local route_iface=$(ip route | awk '/default via.*dev/ {print $5}' | grep -E 'wlan[0-9]+|wl[0-9]+|ra[0-9]+')
    
    if [ -n "$route_iface" ]; then
        echo "$route_iface"
        return
    fi
    
    # 方法2：检查所有无线接口的模式
    for iface in $(iw dev | grep Interface | awk '{print $2}'); do
        local mode=$(iw dev $iface info | grep type | awk '{print $2}')
        if [ "$mode" = "managed" ]; then
            echo "$iface"
            return
        fi
    done
    
    # 方法3：尝试常见接口名
    for iface in wlan0 wl0 wlan1; do
        if iw dev $iface info >/dev/null 2>&1; then
            echo "$iface"
            return
        fi
    done
    
    # 如果都失败则返回默认值
    echo "wlan0"
}

# 使用自动检测的接口
WIFI_IFACE=$(detect_wifi_iface)
TARGET_IP="8.8.8.8"  # Google DNS

# 记录使用的接口到日志
logger -t WiFiCheck "使用检测到的接口: $WIFI_IFACE"

# 检测网络连通性
if ! ping -c 2 -W 3 -I $WIFI_IFACE $TARGET_IP >/dev/null 2>&1; then
    logger -t WiFiCheck "网络异常! 重启WiFi..."
    wifi down
    sleep 2
    wifi up
    
    # 再次检测网络状态
    sleep 10
    if ping -c 1 -W 3 -I $WIFI_IFACE $TARGET_IP >/dev/null 2>&1; then
        logger -t WiFiCheck "WiFi重启成功，网络恢复"
    else
        logger -t WiFiCheck "警告: WiFi重启后仍未恢复!"
    fi
fi
